﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Navigation;
using Microsoft.Phone.Controls;
using Microsoft.Phone.Shell;
using System.Text.RegularExpressions;
using System.Windows.Media.Imaging;
using ODS.WebService.AccountFuntions;
using ODS.Utils;
using ODS.Model;
using ODS.Config;

namespace ODS
{
    public partial class ProfilePage : PhoneApplicationPage
    {
        //bool IsLoginNameOk = true;
        bool IsUsernameOk = true;
        bool IsOldPasswordOk = true;
        bool IsNewPasswordOk = true;
        bool IsReNewPasswordOk = true;
        bool IsEmailOk = true;
        bool IsPhoneNumberOk = true;

        public ProfilePage()
        {
            InitializeComponent();

            tb_username.MyText = App.userLogin.UserLoginName;
            OldPassword.Password = App.userLogin.UserPassword;

            CheckOldPasswordWatermark();
        }

        protected override async void OnNavigatedTo(NavigationEventArgs e)
        {
            base.OnNavigatedTo(e);

           InfoResult result = await RetrieveAccountDetailService.RetrieveAccountDetail();
           if (result.IsSuccess)
           {
               if (result.ReturnedObject != null)
               {
                   UserAccountModel userAccount = result.ReturnedObject as UserAccountModel;
                   userAccount.UserLoginName = App.userLogin.UserLoginName;
                   userAccount.UserPassword = App.userLogin.UserPassword;
                   App.userLogin = userAccount;
                   setInfoOfUser(userAccount);
               }
           }
 
        }

        void setInfoOfUser(UserAccountModel userAccount)
        {
            tb_username.MyText = userAccount.UserLoginName;
            OldPassword.Password = userAccount.UserPassword;
            tb_notificationInfo.MyText = userAccount.UserNotificationEmail;

            if (userAccount.UserNotificationEmail != null && userAccount.UserNotificationEmail.Length > 0)
            {
                img_notificationInfo.Source = new BitmapImage(new Uri("/Assets/images/tick icon.png", UriKind.Relative));
                IsEmailOk = true;
            }

            if (userAccount.UserMobileNumber != null && userAccount.UserMobileNumber.Length > 0)
            {
                tb_mobileNumber.MyText = "+" + userAccount.UserMobileNumber;

                img_contactDetail.Source = new BitmapImage(new Uri("/Assets/images/tick icon.png", UriKind.Relative));
                IsPhoneNumberOk = true;
            }

            
        }

        private void btn_back_Click(object sender, System.Windows.RoutedEventArgs e)
        {
            NavigationService.GoBack();
        }

        private async void btn_apply_Click(object sender, System.Windows.RoutedEventArgs e)
        {
            if (!ValidateInput())
            {
                return;
            }

            if ((tb_mobileNumber.MyText == App.userLogin.UserMobileNumber ) && (tb_notificationInfo.MyText == App.userLogin.UserNotificationEmail) && (tb_username.MyText == App.userLogin.UserLoginName))
            {
                MessageBox.Show("Data haven't changed");
                return;
            }

            ShowWaiting();

            bool IsUpdateError = false;

            if (OldPassword.Password.Length > 0 && NewPassword.Password.Length > 0)
            {
                InfoResult result = await ChangePasswordService.ChangePassword(OldPassword.Password, NewPassword.Password);
                if (result.IsSuccess)
                {
                    if ((String)result.ReturnedObject == Constants.SUCCESS)
                    {
                        MessageBox.Show("Change password successful.");

                        App.userLogin.UserLoginName = tb_username.MyText;
                        App.userLogin.UserPassword = NewPassword.Password;

                        Setting.Set(Constants.KEY_USERNAME, App.userLogin.UserLoginName);
                        Setting.Set(Constants.KEY_PASSWORD, App.userLogin.UserPassword);

                        
                    }
                    else
                    {
                        MessageBox.Show((String)result.ReturnedObject);
                        IsUpdateError = true;
                    }
                }
                else
                {
                    MessageBox.Show(result.Error);
                    IsUpdateError = true;
                }
            }

            if (tb_notificationInfo.MyText.Length > 0 || tb_mobileNumber.MyText.Length > 0)
            {
                if (!tb_mobileNumber.MyText.Equals(App.userLogin.UserMobileNumber) && !tb_notificationInfo.MyText.Equals(App.userLogin.UserNotificationEmail))
                {
                    App.userLogin.UserCountry = "702";
                    InfoResult result = await ChangeAccountDetailService.ChangeAccountDetail(App.userLogin);
                    if (result.IsSuccess)
                    {
                        if ((String)result.ReturnedObject == Constants.SUCCESS)
                        {
                            MessageBox.Show("Change account details successful.");
                        }
                        else
                        {
                            MessageBox.Show((String)result.ReturnedObject);
                            IsUpdateError = true;
                        }
                    }
                    else
                    {
                        MessageBox.Show(result.Error);
                        IsUpdateError = true;
                    }
                }
            }

            if (!IsUpdateError)
            {
                App.BackToMainPage(this);
            }

            HiddenWaiting();
        }

        #region Old password
        private void OldPasswordLostFocus(object sender, RoutedEventArgs e)
        {
            CheckOldPasswordWatermark();
        }

        public void CheckOldPasswordWatermark()
        {
            var passwordEmpty = string.IsNullOrEmpty(OldPassword.Password);
            OldPasswordWatermark.Opacity = passwordEmpty ? 100 : 0;
            OldPassword.Opacity = passwordEmpty ? 0 : 100;
        }

        private void OldPasswordGotFocus(object sender, RoutedEventArgs e)
        {
            OldPasswordWatermark.Opacity = 0;
            OldPassword.Opacity = 100;
        }

        #endregion

        #region New password
        private void NewPasswordLostFocus(object sender, RoutedEventArgs e)
        {
            CheckNewPasswordWatermark();
        }

        public void CheckNewPasswordWatermark()
        {
            var passwordEmpty = string.IsNullOrEmpty(NewPassword.Password);
            NewPasswordWatermark.Opacity = passwordEmpty ? 100 : 0;
            NewPassword.Opacity = passwordEmpty ? 0 : 100;
        }

        private void NewPasswordGotFocus(object sender, RoutedEventArgs e)
        {
            NewPasswordWatermark.Opacity = 0;
            NewPassword.Opacity = 100;
        }

        #endregion

        #region Renew password
        private void RenewPasswordLostFocus(object sender, RoutedEventArgs e)
        {
            CheckRenewPasswordWatermark();
        }

        public void CheckRenewPasswordWatermark()
        {
            var passwordEmpty = string.IsNullOrEmpty(RenewPassword.Password);
            RenewPasswordWatermark.Opacity = passwordEmpty ? 100 : 0;
            RenewPassword.Opacity = passwordEmpty ? 0 : 100;
        }

        private void RenewPasswordGotFocus(object sender, RoutedEventArgs e)
        {
            RenewPasswordWatermark.Opacity = 0;
            RenewPassword.Opacity = 100;
        }
        #endregion

        #region validate input
        //private void tb_loginName_TextChanged(object sender, System.Windows.Controls.TextChangedEventArgs e)
        //{
        //    if (IsLoginNameOk = (tb_loginName.MyText == "" ||  Regex.IsMatch(tb_loginName.MyText, "^([a-zA-Z]{1,})$")))
        //    {
        //        img_checkLoginName.Source = new BitmapImage(new Uri("/Assets/images/tick icon.png", UriKind.Relative));
        //    }
        //    else
        //    {
        //        img_checkLoginName.Source = new BitmapImage(new Uri("/Assets/images/grey tick.png", UriKind.Relative));
        //    }
        //}

        private void tb_username_TextChanged(object sender, System.Windows.Controls.TextChangedEventArgs e)
        {

            if (IsUsernameOk = Regex.IsMatch(tb_username.MyText, @"^((([\w]+\.[\w]+)+)|([\w]+))@(([\w]+\.)+)([A-Za-z]{1,3})$"))
            {
                img_checkUsername.Source = new BitmapImage(new Uri("/Assets/images/tick icon.png", UriKind.Relative));
            }
            else
            {
                img_checkUsername.Source = new BitmapImage(new Uri("/Assets/images/grey tick.png", UriKind.Relative));
            }
        }

        private void OldPassword_PasswordChanged(object sender, System.Windows.RoutedEventArgs e)
        {
            if ( IsOldPasswordOk = Regex.IsMatch(OldPassword.Password, @"^(.{8,})$"))
            {
                img_checkCurrentPassword.Source = new BitmapImage(new Uri("/Assets/images/tick icon.png", UriKind.Relative));
            }
            else
            {
                img_checkCurrentPassword.Source = new BitmapImage(new Uri("/Assets/images/grey tick.png", UriKind.Relative));
            }
        }

        private void NewPassword_PasswordChanged(object sender, System.Windows.RoutedEventArgs e)
        {
            IsNewPasswordOk = (NewPassword.Password == "" ||Regex.IsMatch(NewPassword.Password, @"^(.{8,})$") );
            if (Regex.IsMatch(NewPassword.Password, @"^(.{8,})$"))
            {
                img_newPassword.Source = new BitmapImage(new Uri("/Assets/images/tick icon.png", UriKind.Relative));
            }
            else
            {
                img_newPassword.Source = new BitmapImage(new Uri("/Assets/images/grey tick.png", UriKind.Relative));
            }

            if (IsReNewPasswordOk = (Regex.IsMatch(RenewPassword.Password, @"^(.{8,})$") && RenewPassword.Password.Equals(NewPassword.Password)))
            {
                img_reNewPassword.Source = new BitmapImage(new Uri("/Assets/images/tick icon.png", UriKind.Relative));
            }
            else
            {
                img_reNewPassword.Source = new BitmapImage(new Uri("/Assets/images/grey tick.png", UriKind.Relative));
            }
        }

        private void RenewPassword_PasswordChanged(object sender, System.Windows.RoutedEventArgs e)
        {
            IsReNewPasswordOk = (RenewPassword.Password == "" || (Regex.IsMatch(RenewPassword.Password, @"^(.{8,})$") && RenewPassword.Password.Equals(NewPassword.Password)));
            if ((Regex.IsMatch(RenewPassword.Password, @"^(.{8,})$") && RenewPassword.Password.Equals(NewPassword.Password)))
            {
                img_reNewPassword.Source = new BitmapImage(new Uri("/Assets/images/tick icon.png", UriKind.Relative));
            }
            else
            {
                img_reNewPassword.Source = new BitmapImage(new Uri("/Assets/images/grey tick.png", UriKind.Relative));
            }
        }

        private void tb_notificationInfo_TextChanged(object sender, System.Windows.Controls.TextChangedEventArgs e)
        {
            IsPhoneNumberOk = ((tb_mobileNumber.MyText == "" && tb_notificationInfo.MyText == "") || Regex.IsMatch(tb_mobileNumber.MyText, @"^((?:\+|\-|[0-9])([0-9]{9,15}))$"));
            IsEmailOk = ((tb_notificationInfo.MyText == "" && tb_mobileNumber.MyText =="") || Regex.IsMatch(tb_notificationInfo.MyText, @"^((([\w]+\.[\w]+)+)|([\w]+))@(([\w]+\.)+)([A-Za-z]{1,3})$"));
            if (Regex.IsMatch(tb_notificationInfo.MyText, @"^((([\w]+\.[\w]+)+)|([\w]+))@(([\w]+\.)+)([A-Za-z]{1,3})$"))
            {
                img_notificationInfo.Source = new BitmapImage(new Uri("/Assets/images/tick icon.png", UriKind.Relative));
            }
            else
            {
                img_notificationInfo.Source = new BitmapImage(new Uri("/Assets/images/grey tick.png", UriKind.Relative));
            }
        }

        private void tb_mobileNumber_TextChanged(object sender, System.Windows.Controls.TextChangedEventArgs e)
        {
            IsPhoneNumberOk = ((tb_mobileNumber.MyText == "" && tb_notificationInfo.MyText =="") || Regex.IsMatch(tb_mobileNumber.MyText, @"^((?:\+|\-|[0-9])([0-9]{9,15}))$"));
            IsEmailOk = ((tb_notificationInfo.MyText == "" && tb_mobileNumber.MyText == "") || Regex.IsMatch(tb_notificationInfo.MyText, @"^((([\w]+\.[\w]+)+)|([\w]+))@(([\w]+\.)+)([A-Za-z]{1,3})$"));
            
            if (Regex.IsMatch(tb_mobileNumber.MyText, @"^((?:\+|\-|[0-9])([0-9]{9,15}))$"))
            {
                img_contactDetail.Source = new BitmapImage(new Uri("/Assets/images/tick icon.png", UriKind.Relative));
            }
            else
            {
                img_contactDetail.Source = new BitmapImage(new Uri("/Assets/images/grey tick.png", UriKind.Relative));
            }
        }

        #endregion

        bool ValidateInput()
        {
            //if (!IsLoginNameOk)
            //{
            //    MessageBox.Show("Login name alphabets only, please try again.");
            //    return false;
            //}

            if (!IsUsernameOk)
            {
                MessageBox.Show("Username alpha numuric only, please try again.");
                return false;
            }

            if (!IsOldPasswordOk)
            {
                MessageBox.Show("Incorrect current password, please try again.");
                return false;
            }

            if (!IsNewPasswordOk)
            {
                MessageBox.Show("Incorrect New Password, please try again.");
                return false;
            }

            if (!IsReNewPasswordOk)
            {
                MessageBox.Show("Incorrect Retype Password, please try again.");
                return false;
            }

            if (!IsEmailOk)
            {
                MessageBox.Show("Incorrect Email, please try again.");
                return false;
            }

            if (!IsPhoneNumberOk)
            {
                MessageBox.Show("Incorrect Mobile, please try again with as format +849...");
                return false;
            }

            return true;
        }

        void ShowWaiting()
        {
            progressBar_waiting.Visibility = Visibility.Visible;
            tb_username.IsEnabled = false;
            OldPassword.IsEnabled = false;
            NewPassword.IsEnabled = false;
            RenewPassword.IsEnabled = false;
            tb_mobileNumber.IsEnabled = false;
            tb_notificationInfo.IsEnabled = false;
        }

        void HiddenWaiting()
        {
            progressBar_waiting.Visibility = Visibility.Collapsed;
            tb_username.IsEnabled = true;
            OldPassword.IsEnabled = true;
            NewPassword.IsEnabled = true;
            RenewPassword.IsEnabled = true;
            tb_mobileNumber.IsEnabled = true;
            tb_notificationInfo.IsEnabled = true;
        }
    }
}